import React, {useState} from 'react'
import { useNavigate } from 'react-router-dom'
import { Button, Form, Input, Toast } from 'antd-mobile'
import { RightOutline, CloseOutline } from 'antd-mobile-icons'
import { addUser } from '../../api/index'
import './index.css'

export default function Register() {
  const [account, setAccount] = useState('')
  const [password, setPassword] = useState('')
  const [againPassword, setAgainPassword] = useState('')
  const navigate = useNavigate()
  const register = async()=>{
    if(password === againPassword){
      try {
        const result = await addUser({
          account,
          password
        })
        Toast.show({icon: 'success', content: result.data.message, maskClickable:false})
        setTimeout(() => {
          navigate(-1)
        }, 2000);
      } catch (error) {
        Toast.show({icon: 'fail', content: error.message, maskClickable:false})
      }
    }else{
      Toast.show({icon: 'fail', content: '两次密码输入不一致！', maskClickable:false})
    }
    
  }

  const back = ()=>{
    navigate(-1)
  }

  return (
    <div id='register'> 
      <div style={{padding:'20px', fontSize:'30px', textAlign:'right'}}><CloseOutline onClick={back}/></div>
      <div className='register-box'>
        <Form layout='horizontal' mode='card'>
          <Form.Item label='账号'>
            <Input placeholder='请输入' value={account} onChange={val => setAccount(val)} />
          </Form.Item>
          <Form.Item label='密码'>
            <Input type='password' placeholder='请输入' value={password} onChange={val => setPassword(val)} />
          </Form.Item>
          <Form.Item label='确认密码'>
            <Input type='password' placeholder='请输入' value={againPassword} onChange={val => setAgainPassword(val)} />
          </Form.Item>
        </Form>
        <Button className='next' onClick={register} style={{width:'60px',height:'60px',fontSize:'30px','--border-width':'2px'}} shape='rounded' color='primary' fill='outline'><RightOutline /></Button>
      </div>
    </div>
  )
}
